using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using SpellCenter.Core;
using SpellCenter.UI;
using SpellCenter.UI.Properties;

namespace SpellCenter.UI
{
    public partial class WordContextControl : UserControl, IWordContext
    {
        private readonly IInterApplicationSyncronizer _classClown;
        private readonly WordContextControlPM _model;
        public WordContextControlPM Model
        {
            get{ return _model;}
        }

        private readonly bool _hasBeenInitialized = false;
        public WordContextControl()
        {
            InitializeComponent();
            _model = new WordContextControlPM();
            _contextCol.Model = _model;
            _classClown = new SantaFeSynchronizer();
            PimpOutDataGrid();
            RegisterEvents();
            _hasBeenInitialized = true;
        }

        #region Events

        private void RegisterEvents()
        {
            _grid.ColumnWidthChanged += Grid_ColumnWidthChanged;
            _grid.DoubleClick += Grid_DoubleClick;
        }

        private void Grid_DoubleClick(object sender, EventArgs e)
        {
            if(_grid.SelectedRows.Count > 0)
            {
                int row = _grid.SelectedRows[0].Index;
                WordContext word = _model.Data[row];
                string reference = word.Reference;

                try
                {
                    _classClown.MoveToVerse(reference);
                }
                catch (YouDontKnowWhatABibleVerseLooksLikeException)
                {
                    MessageBox.Show("this word doesn't have a valid verse number");
                }
            }
        }

        private void Grid_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            if(_hasBeenInitialized)
            {
                _contextCol.Width = _grid.DisplayRectangle.Width - _referenceCol.Width;
                Settings.Default.ContextGrid_RefColumnWidth = _referenceCol.Width;
                Settings.Default.Save();
            }
        }

        #endregion


        private void PimpOutDataGrid()
        {
            _grid.ScrollBars = ScrollBars.Vertical;
            _grid.BackgroundColor = Color.Ivory;
            _grid.AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue;
            _grid.AlternatingRowsDefaultCellStyle.SelectionBackColor = Color.CornflowerBlue;
            _grid.AlternatingRowsDefaultCellStyle.SelectionForeColor = Color.Black;
            _grid.DefaultCellStyle.BackColor = Color.GhostWhite;
            _grid.DefaultCellStyle.SelectionBackColor = Color.CornflowerBlue;
            _grid.DefaultCellStyle.SelectionForeColor = Color.Black;

            _referenceCol.Width = Settings.Default.ContextGrid_RefColumnWidth;
        }

        private void WordContextControl_Resize(object sender, EventArgs e)
        {
            _grid.Size = Size;
            _contextCol.Width = Width - _referenceCol.Width;
        }

        private static readonly int s_largestPossibleScreenWidth = SumOfScreenWidths();

        public void SetWords(IList<SpellWordInfo> words)
        {
            _model.SetSpellWords(words);
            _model.DoneWaiting += BackgroundWorker_DoneWaiting;
            _model.Waiting += BackgroundWorker_Waiting;
        }

        private static int SumOfScreenWidths()
        {
            int ret = 0;
            foreach (Screen screen in Screen.AllScreens)
                ret += screen.Bounds.Width;
            Debug.Assert(ret > 100, string.Format("Sum of screen widths is {0}? That must be too small", ret));
            return ret;
        }

        public void UseWord(int iword)
        {
            _model.FillContextByPixelWidth(iword,
                        // get the largest possible width that the window can be, but chop the rest to save on memory
                        s_largestPossibleScreenWidth,
                        _grid.Font);
            _wordContextBindingSource.DataSource = _model.Data;
            SetFont(Settings.Default.GridFont);
        }

        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            _grid.Rows[e.RowIndex].Selected = true;
        }

        public void SetFont(Font font)
        {
            Font tmp = _grid.DefaultCellStyle.Font;
            if(tmp != _referenceCol.HeaderCell.Style.Font && _referenceCol.HeaderCell.Style.Font != null)
            {
                tmp = _referenceCol.HeaderCell.Style.Font;
            }
            _grid.Font = font;
            _referenceCol.HeaderCell.Style.Font = tmp;
            _contextCol.HeaderCell.Style.Font = tmp;
            _grid.AutoResizeRows();
        }

        #region Waiting and DoneWaiting events

        private void BackgroundWorker_DoneWaiting(object sender, EventArgs e)
        {
            DoneWaiting(sender, e);
        }

        private void BackgroundWorker_Waiting(object sender, EventArgs e)
        {
            Waiting(sender, e);
        }

        public event EventHandler<EventArgs> Waiting;
        public event EventHandler<EventArgs> DoneWaiting;

        #endregion
    }
}